package com.education.common.interceptor;

import com.education.common.model.JwtToken;
import com.education.common.util.ObjectUtils;
import com.education.common.util.RequestUtils;
import com.education.common.util.Result;
import com.education.common.util.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 余一
 * @date 2021/9/28  15:03
 */
public abstract class BaseInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class);

    /**
     * 校验token是否合法
     * @param jwtToken
     * @param request
     * @param response
     * @return
     */
    protected boolean checkToken(JwtToken jwtToken, HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("token");
        String userId = jwtToken.parseTokenToString(token);
        //token不存在或token失效
        if (ObjectUtils.isEmpty(token) || ObjectUtils.isEmpty(userId)) {
            logger.warn("token不存在或token失效");
            Result.renderJson(response,Result.fail(ResultCode.UN_AUTH_ERROR_CODE,"用户未认证"));
            return false;
        }
        return true;
    }

    /**
     * 获取json参数值
     * @param request
     * @return
     */
    protected String readData(HttpServletRequest request){
        return RequestUtils.readData(request);
    }
}
